Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

144
Vistas
Transforming a list of points in a "rank" of indexes

Let's say that I have a list of points from a torunament

points = [0, 12, 9]

And I want to have a ranking of the players, so the expected outputs would be

[1, 2, 0]

Because the index 1 is first in the ranking, followed by index 2 and then index 0. My idea was to use a for to iterate through all the numbers, getting the biggest value, find the index of the biggest value and then assign the value in the ranking, but it seems unnecessary long and complicated. Any tips?

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

Use sorted:

points = [0, 12, 9]
res = sorted(range(len(points)), key=lambda x: points[x], reverse=True)
print(res)

Output

[1, 2, 0]

The idea is to sort the indexes of the list (range(3)) according to their value on the list, hence the key=lambda x: points[x]. The reverse True is because you want a descending ranking.

over 4 years ago · Santiago Trujillo Denunciar

0

points = [0, 12, 9]
points_and_indices = [(p, i) for i, p in enumerate(points)]
points_and_indices.sort(reverse=True)
indices = [i for p, i in points_and_indices]
print(indices)

output:

[1, 2, 0]

UPDATE

You say in a comment

The first index who got that number of points is ahead

Unfortunately this causes the above solution to be wrong for your purposes, because the indices are included in the reverse sort.

To exploit the stability of Python sorts we must either not include the indices in the reverse sort, or use a decreasing function of the points instead of the points themselves.

We can sort according to the negative points, and also condense it all into a one-liner, like this:

points = [0, 12, 9, 12]
indices = [i for _, i in sorted((-p, i) for i, p in enumerate(points))]
print(indices)

output:

[1, 3, 2, 0]

Anyway, the solution by Dani Mesejo is more pythonic, even though the use of a sort key may cause some head scratching in people coming from other programming languages.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda